<?php defined('SYSPATH') OR die('No direct access allowed.');

class Menu_Controller extends Controller {

	public function __construct()
	{
		parent::__construct();
		$this->menu_model = new Menu_Model;	
		$this->stok_model = new Stok_Model;
        $this->membutuhkan_model = new Membutuhkan_Model;
	}
	
	public function index()
	{		
		if(!parent::_authenticate()) {
			return;
		}
		parent::_loadContent("Daftar Menu", 'menu_content');		
		$this->view->content->menus = $this->menu_model;
		$this->view->content->stoks = $this->stok_model->get_all_stok();
		if(!empty($_POST)) {
				$this->validation = new Validation($_POST);
				$this->validation->add_rules('ID_menu','required','length[1,10]');
				$this->validation->add_rules('nama_menu','required','standard_text');
				$this->validation->add_rules('harga_jual','required','numeric');
				
				$this->validation->add_callbacks('ID_menu',array($this,'_ID_menu_check'));
				$this->validation->add_callbacks('harga_jual',array($this,'_harga_jual_check'));
				
				if($this->validation->validate()) {
					$this->menu_model->insert_menu(array('ID_menu'=>$this->input->post('ID_menu'),'nama_menu'=>$this->input->post('nama_menu'),'harga_jual'=>$this->input->post('harga_jual')));
					foreach($this->input->post() as $key=>$val) {
						if($key=='ID_menu' || $key=='nama_menu' || $key=='harga_jual') {
							continue;
						}//key selebihnya adalah id_stok bahan menu tersebut
						if($val>0) {
							$this->membutuhkan_model->insert_membutuhkan($key,$this->input->post('ID_menu'),$val);
						}
					}
				}else{
					$this->view->content->errors = $this->validation->errors('menu_error');
				}
		}
		$this->view->render(TRUE);
	}
	
	public function _ID_menu_check(Validation $post) {
		if(array_key_exists('ID_menu',$post->errors())) {
			return;
		}
		if($this->menu_model->check_already_exist_menu($post->ID_menu)) {
			$post->add_error('ID_menu','_ID_menu_check');
		}
	}
	
	public function _harga_jual_check(Validation $post) {
		if(array_key_exists('harga_jual',$post->errors())) {
			return;
		}
		if(intval($post->harga_jual)<0) {
			$post->add_error('harga_jual','_harga_jual_check');
		}
	}
}